import React, { useEffect, useState } from 'react';
import {
  View,
  Image,
  Input
} from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import {
  AtFloatLayout,
  AtActionSheet,
  AtActionSheetItem
} from 'taro-ui';
import {
  NavBar,
  ModalTemplate
} from '@/components';
import {
  queryUserArchivesList,
  postUserArchivesEdit,
  postUserArchivesDel
} from "@/api";
import { useDispatch, useSelector } from 'react-redux';
import { updateToken, updateShowTemplates } from '@stores/actions/user';
import './index.scss';

const Mine = () => {
  const dispatch = useDispatch();
  const user = useSelector((state)=>state.user)
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [showTemmplate, setShowTemplate] = useState(false);
  const [selectId, setSelectId] = useState(null);
  const [delId, setDelId] = useState(null);
  const [showDelete, setShwoDelete] = useState(false);
  const [list, setList] = useState([]);
  const [name, setName] = useState('');

  const [errorsList] = useState([
    {
      id: 0,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_side.png',
      name: '侧面'
    },
    {
      id: 1,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_occlusion.png',
      name: '有遮挡'
    },
    {
      id: 2,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_dark.png',
      name: '光线暗'
    },
    {
      id: 3,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_vague.png',
      name: '模糊'
    }
  ]);

  useDidShow(() => {
    if (user.showTemmplates) {
      setShowTemplate(true);
      dispatch(updateShowTemplates(false));
    }
    Taro.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    onLoadData();
  });

  const onLoadData = () => {
    queryUserArchivesList({})
      .then(res=>{
        setList(res.list);
      })
  }

  const onShowRemoveAction = (id, e) => {
    e.stopPropagation();
    Taro.showActionSheet({
      itemList: ['删除'],
      itemColor: '#1B1B1B',
      success: function (res) {
        console.log(res.tapIndex)
        let {
          tapIndex
        } = res;
        if (tapIndex === 0) {
          postUserArchivesDel({id: id})
            .then(response=>{
              Taro.showToast({
                title: '删除成功',
                icon: 'none',
                success: () => {
                  // setShwoDelete(false);
                  // setDelId(null);
                  onLoadData();
                }
              });
            })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  }

  const onAddProfile = (e) => {
    e.stopPropagation();
    setShowTemplate(true);
  }

  const onClose = () => {
    setShowTemplate(false)
  }

  const onChange = (event) => {
    let value = event.detail.value;
    // if (value.length >= 6) {
    //   Taro.showToast({
    //     title: '名称不能超过6个字符',
    //     icon: 'none'
    //   });
    //   return;
    // }
    // else {
    //   setName(value);
    // }
    setName(value);
  }

  const onSureChangeName = () => {
    if (name.length > 6) {
      Taro.showToast({
        title: '名称不能超过6个字符',
        icon: 'none'
      });
      setName('');
      setSelectId(null);
      return;
    }
    else {
      postUserArchivesEdit({id: selectId, archives_name: name})
        .then(res=>{
          Taro.showToast({
            title: '修改成功',
            icon: 'none',
            success: () => {
              setName('');
              setSelectId(null);
              onLoadData();
            }
          });
        })
        .catch(err=>{
          Taro.showToast({
            title: '修改失败',
            icon: 'none'
          })
        })
    }
  }

  const onChooseName = (id, e) => {
    e.stopPropagation();
    let targetName = '';
    list.forEach(item=>{
      if (item.id == id) {
        targetName = item.archives_name
      }
    });
    setName(targetName);
    setSelectId(id);
  }

  const onSureDelete = () => {
    postUserArchivesDel({id: delId})
      .then(res=>{
        Taro.showToast({
          title: '删除成功',
          icon: 'none',
          success: () => {
            setShwoDelete(false);
            setDelId(null);
            onLoadData();
          }
        });
      })
  }

  return (
    <View className='faceprofile_container'>
      {/* <NavBar
        title="我的脸部档案"
        onClick={()=>{doBack()}}
      /> */}
      <View
        className='faceprofile_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View
          className='faceprofile_view'
          style={{
            height: `calc(100vh - ${titleBarHeight}px)`
          }}
        >
          {
            list.map(item=>
              <View className='faceprofile_view_section' key={item.id}>
                <View className='faceprofile_view_section_main'>
                  <Image
                    src={item.archives_img}
                    className='faceprofile_view_section_main_img'
                    mode='aspectFill'
                  />
                </View>
                <Input
                  className='faceprofile_view_section_name'
                  value={item.id == selectId ? name : item.archives_name}
                  disabled={item.id == selectId ? false : true}
                  focus={item.id == selectId ? true : false}
                  onInput={(e)=>{onChange(e)}}
                  maxlength={6}
                  onConfirm={()=>{onSureChangeName()}}
                />
                <View className='faceprofile_view_section_actions'>
                  <View
                    className='faceprofile_view_section_actions_item del'
                    onClick={(e)=>{onShowRemoveAction(item.id,e)}}
                  >
                    删除
                  </View>
                  <View
                    className='faceprofile_view_section_actions_item edit'
                    onClick={(e)=>{onChooseName(item.id, e)}}
                  >
                    修改名称
                  </View>
                </View>
              </View>
            )
          }
        </View>
      </View>
      <View
        className='faceprofile_section_add'
        onClick={(e)=>{onAddProfile(e)}}
      >
        添加脸部档案
      </View>
      {
        showTemmplate ? (
          <ModalTemplate
            showTemmplate={showTemmplate}
            onClick={()=>{onClose()}}
            errorsList={errorsList}
            onClose={()=>{setShowTemplate(false)}}
          />
        ) : null
      }
      <AtActionSheet
        isOpened={showDelete}
        cancelText='取消'
      >
        <AtActionSheetItem onClick={()=>{onSureDelete()}}>
          删除
        </AtActionSheetItem>
      </AtActionSheet>
    </View>
  )
}
export default Mine;
